package operation;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Properties;
import java.util.Vector;
import java.util.stream.Collectors;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;



public class TomcatManageService {
	
	private static final String TOMCAT_FIND = "find %s -name \"*tomcat*\" -type d -exec ls -ld {} \\;|awk '{existsDir=system(\"test -d \"$9\"/bin && test -d \"$9\"/webapps && test -d \"$9\"/conf && test -d \"$9\"/lib && test -f \"$9\"/bin/startup.sh\");if(!existsDir){print $9\" \"$0}}'";
	private static final String TOMCAT_RUNNING = "ps -ef | grep java | grep tomcat | gawk '{match($0,\"catalina.home\\=([^ ]+)\",path);if(null != path[1]){print $2\" \"$1\" \"path[1]}}'";
	private static final String TOMCAT_KILL = "kill -9 `ps -ef | grep java | grep tomcat | grep '%s' | grep '%s' | awk '{print $2}'`";
	private static final String TOMCAT_START = "source /etc/profile && sh '%s/bin/startup.sh'";
	private static final String SHELL_GAWK_SUPPORT = "gawk -V";
	private static final String TOMCAT_RUNNING_SCHEME2 = "ps -ef | grep java | grep tomcat | sed 's//'";
	
	private static TomcatManageService tomcatManageService;
	
	private TomcatManageDao manageDao = new TomcatManageDao();
	
	public static void main(String[] args) throws Exception {
		//new TomcatManageService().createConnection();
		
//		System.out.println(TomcatManageService.getInstance().getTomcatInfo());
//		TomcatManageService.getInstance().close();
//		System.out.println(TomcatManageService.getInstance().getTomcatInfo());
//		System.out.println(TomcatManageService.getInstance().getTomcatInfo());
//		TomcatManageService.getInstance().close();
		
		TomcatManageService.getInstance().startTomcat(TOMCAT_RUNNING_SCHEME2);
		TomcatManageService.getInstance().close();
	}
	
	public static TomcatManageService getInstance(){
		if(null == tomcatManageService){
			tomcatManageService = new TomcatManageService();
		}
		return tomcatManageService;
	}
	
	public List<TomcatManageFacadeElement> getTomcatInfo(){
		List<TomcatDirElement> dirElements = searchTomcatPath("/");
		List<TomcatProcessElement> processElements = showTomcatStarted();
		close();
		List<TomcatManageFacadeElement> elements = dirElements.stream().map(dirEle->{
			TomcatManageFacadeElement element = new TomcatManageFacadeElement();
			element.setPath(dirEle.getPath());
			element.setFileUser(dirEle.getUser());
			element.setFileGroup(dirEle.getGroup());
			return element;
		}).collect(Collectors.toList());
		processElements.forEach(processEle->
			elements.forEach(ele->{
				if(!Objects.equals(processEle.getPath(),ele.getPath()))return;
				ele.setPid(processEle.getPid());
				ele.setRunUser(processEle.getUser());
			})
		);
		return elements;
	}
	
	/**
	 * 鏌ヨ鍒版墍鏈夌殑tomcat鐩綍浣嶇疆
	 * @param path
	 */
	public List<TomcatDirElement> searchTomcatPath(String...path){
		if(null == path){
			path = new String[]{"/"};
		}
		ChannelExec channelExec = null;
		BufferedReader bufferedReader = null;
		try {
			channelExec = manageDao.createChannelExec();
			List<TomcatDirElement> result = new ArrayList<>();
			for(String p : path){
				channelExec.setCommand(String.format(TOMCAT_FIND, p));
				channelExec.connect();
				bufferedReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
				result.addAll(bufferedReader.lines().map(o->new TomcatDirElement(o)).collect(Collectors.toList()));
			}
			return result;
		} catch (JSchException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(bufferedReader);
			close(channelExec);
		}
		return Collections.emptyList();
	}
	/**
	 * 鏌ヨ姝ｅ湪杩愯涓殑tomcat鐩綍
	 */
	public List<TomcatProcessElement> showTomcatStarted(){
		ChannelExec channelExec = null;
		BufferedReader bufferedReader = null;
		try {
			channelExec = manageDao.createChannelExec();
			channelExec.setCommand(TOMCAT_RUNNING);
			channelExec.connect();
			bufferedReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
			return bufferedReader.lines().map(o->new TomcatProcessElement(o)).collect(Collectors.toList());
		} catch (JSchException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			close(bufferedReader);
			close(channelExec);
		}
		return Collections.emptyList();
	}

	public int stopTomcat(String pid, String path){
		ChannelExec channelExec = null;
		BufferedReader bufferedReader = null;
		try {
			channelExec = manageDao.createChannelExec();
			channelExec.setCommand(String.format(TOMCAT_KILL, pid, path));
			channelExec.connect();
			return channelExec.getExitStatus();
		} catch (JSchException e) {
			e.printStackTrace();
		} finally {
			close(bufferedReader);
			close(channelExec);
		}
		return 0;
	}
	public int startTomcat(String path){
		ChannelExec channelExec = null;
		BufferedReader bufferedReader = null;
		try {
			path = "/home/web/software/install/tomcat7";
			channelExec = manageDao.createChannelExec();
			channelExec.setCommand(String.format(TOMCAT_START, path));
			channelExec.connect();
			bufferedReader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
			bufferedReader.lines().forEach(o->System.out.println(o));
			System.out.println(channelExec.getExitStatus());
			return channelExec.getExitStatus();
		} catch (JSchException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(bufferedReader);
			close(channelExec);
		}
		return 0;
	}
	public void uploadFile(){
		
	}
	public void monitorLog(){
		
	}
	public void close(){
		try {
			manageDao.close();
		} catch (JSchException e) {
			e.printStackTrace();
		}
	}
	private void close(Reader bufferedReader) {
		if(null == bufferedReader)return;
		try {
			bufferedReader.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void close(Channel channelExec) {
		if(null == channelExec) return;
		channelExec.disconnect();
	}
	
	public void createConnection() throws Exception {
		JSch jSch = new JSch();
		Session session = jSch.getSession("root", "39.98.107.143");
		session.setPassword("Scjdqh123");
		Properties sshConfig = new Properties();
		sshConfig.put("StrictHostKeyChecking", "no");
		session.setConfig(sshConfig);
		System.out.println("杩炴帴鎴愬姛");
		session.connect();
		ChannelExec channelShell = (ChannelExec) session.openChannel("exec");
//		channelShell.setCommand("ls /");
		//鏌ヨ鍒版墍鏈夌殑tomcat鏍圭洰褰曚綅缃�
		channelShell.setCommand(String.format(TOMCAT_FIND,"/"));
		//鏌ヨ姝ｅ湪杩愯涓殑tomcat鐩綍
		channelShell.setCommand(TOMCAT_RUNNING);
		//鍏抽棴杩涚▼(鍏ュ弬杩涚▼鍙�)
		//channelShell.setCommand(String.format(TOMCAT_KILL, "xxxxxxxxxxxxx"));
		//鍚姩杩涚▼(鍏ュ弬璺緞)
//		channelShell.setCommand(String.format(TOMCAT_START,"xxxxxxxxxxxxx"));

		channelShell.setInputStream(null);
		OutputStream outputStream = channelShell.getOutputStream();
		InputStream inputStream = channelShell.getInputStream();
		channelShell.connect();
//		BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
//		bufferedWriter.write("ls /");
		BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
		bufferedReader.lines().forEach(o->System.out.println(o));
		channelShell.disconnect();
		
		
		ChannelSftp channelSftp = (ChannelSftp)session.openChannel("sftp");
		channelSftp.connect();
		//鏌ョ湅鏂囦欢鍒楄〃
		Vector vector = channelSftp.ls(String.format("%s/webapps/","/home/web/software/apache-tomcat-9.0.30"));
		vector.forEach(o -> System.out.println(o));
		File file = new File("xxxxxxxxx");
		//鏂囦欢涓婁紶(鍏ュ弬鏈湴璺緞, 鍏ュ弬鐩爣璺緞)
		if(file.exists()){
			System.out.println(file.exists());
			//channelSftp.put(file.getPath(), String.format("%s/webapps/","/home/web/software/apache-tomcat-9.0.30"));
		}
		
		channelSftp.disconnect();
		inputStream.close();
		outputStream.close();
		session.disconnect();
	}
}
